package com.example.rbacmanage.controller.app;

import com.example.rbacmanage.common.Result;
import com.example.rbacmanage.entity.app.Comment;
import com.example.rbacmanage.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/app/comment")
public class AppCommentController {
    @Autowired
    private CommentService commentService;

    @GetMapping("/list")
    public Result list(Comment commentQuery){
        List<Comment> list = commentService.getAll(commentQuery);
        List<Long> parentIds = list.stream().map(Comment::getParentId).distinct().collect(Collectors.toUnmodifiableList());
        List<Comment> parentComments = new ArrayList<>();
        if (parentIds != null && !parentIds.isEmpty()){
            Comment commentParent = new Comment();
            commentParent.setIds(parentIds);
            parentComments = commentService.getAll(commentParent);
        }

        List<Comment> last = new ArrayList<>();
        for (Comment comment : list){
            for (Comment parentComment : parentComments){
                if (parentComment.getId().equals(comment.getParentId())){
                    comment.setParentNickName(parentComment.getNickName());
                    break;
                }
            }


            List<Comment> children = new ArrayList<>();
            setChildren(children,list,comment);
            comment.setChildren(children);
            if (comment.getParentId() == null || comment.getParentId() == 0){
                last.add(comment);
            }
        }

        return Result.success(last);
    }


    /**
     *
     * @param children 子
     * @param list 总列表
     * @param comment 与之对比的评论
     */
    public void setChildren(List<Comment> children,List<Comment> list,Comment comment){
        for (Comment comment1 : list){
            if (comment1.getParentId().equals(comment.getId())){
                children.add(comment1);
                setChildren(children,list,comment1);
            }
        }
    }

    @PostMapping("/add")
    public Result add(@RequestBody Comment comment){
        comment.setNickName(setNickName());
        comment.setCreateTime(new Date());
        commentService.save(comment);
        return Result.success();
    }
    public String setNickName(){
        int length = ThreadLocalRandom.current().nextInt(4) + 5; // 生成5到8之间的随机数
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            char randomChar = (char)('a' + ThreadLocalRandom.current().nextInt(26)); // 生成'a'到'z'之间的随机字母
            sb.append(randomChar);
        }
        return sb.toString();
    }
}
